import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../models/fishing_spot.dart';
import '../../models/facility.dart';
import '../../providers/fishing_provider.dart';

class FishingPage extends StatefulWidget {
  const FishingPage({super.key});

  @override
  State<FishingPage> createState() => _FishingPageState();
}

class _FishingPageState extends State<FishingPage>
    with TickerProviderStateMixin {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  late TabController _tabController;
  List<FishingSpot> _filteredSpots = [];
  String _searchQuery = '';
  String _selectedFilter = 'all'; // all, nearby, rating, price
  String _selectedDifficulty = 'all'; // all, beginner, intermediate, advanced

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<FishingProvider>().loadFishingSpots();
      _updateFilteredSpots();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    await context.read<FishingProvider>().refreshData();
    _updateFilteredSpots();
  }

  void _onSearch(String query) {
    setState(() {
      _searchQuery = query;
      _updateFilteredSpots();
    });
  }

  void _updateFilteredSpots() {
    final fishingProvider = context.read<FishingProvider>();
    final filtered = fishingProvider.getFilteredSpots(
      searchQuery: _searchQuery,
      filter: _selectedFilter,
      difficulty: _selectedDifficulty,
    );

    setState(() {
      _filteredSpots = filtered;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.white,
      body: CustomScrollView(
        controller: _scrollController,
        physics: const BouncingScrollPhysics(),
        slivers: [
          // Custom AppBar
          _buildSliverAppBar(),

          // Filter Tabs
          SliverToBoxAdapter(
            child: _buildFilterTabs(),
          ),

          // Fishing Spots List
          SliverToBoxAdapter(
            child: SizedBox(
              height: MediaQuery.of(context).size.height - 200,
              child: Consumer<FishingProvider>(
                builder: (context, fishingProvider, child) {
                  if (fishingProvider.isLoading && !fishingProvider.hasLoadedOnce) {
                    return _buildLoadingWidget();
                  }
                  
                  return RefreshIndicator(
                    onRefresh: _onRefresh,
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 40),
                      child: _buildFishingSpotsList(),
                    ),
                  );
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      floating: false,
      pinned: true,
      snap: false,
      stretch: false,
      backgroundColor: Colors.blue[600],
      flexibleSpace: FlexibleSpaceBar(
        title: const Text(
          '钓场',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.blue[600]!,
                Colors.blue[800]!,
              ],
            ),
          ),
        ),
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.search, color: Colors.white),
          onPressed: _showSearchDialog,
        ),
        IconButton(
          icon: const Icon(Icons.filter_list, color: Colors.white),
          onPressed: _showFilterDialog,
        ),
      ],
    );
  }

  Widget _buildFilterTabs() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  _buildFilterChip('全部', 'all'),
                  const SizedBox(width: 8),
                  _buildFilterChip('附近', 'nearby'),
                  const SizedBox(width: 8),
                  _buildFilterChip('高评分', 'rating'),
                  const SizedBox(width: 8),
                  _buildFilterChip('价格', 'price'),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChip(String label, String value) {
    final isSelected = _selectedFilter == value;
    return FilterChip(
      label: Text(label),
      selected: isSelected,
      onSelected: (selected) {
        setState(() {
          _selectedFilter = value;
          _updateFilteredSpots();
        });
      },
      selectedColor: Colors.blue[100],
      checkmarkColor: Colors.blue[600],
    );
  }

  Widget _buildLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text(
            '正在加载钓场信息...',
            style: TextStyle(color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _buildFishingSpotsList() {
    if (_filteredSpots.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _searchQuery.isEmpty ? '暂无钓场信息' : '未找到"$_searchQuery"相关的钓场',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _filteredSpots.length,
        itemBuilder: (context, index) {
          return _buildFishingSpotCard(_filteredSpots[index]);
        },
      ),
    );
  }

  Widget _buildFishingSpotCard(FishingSpot spot) {
    return GestureDetector(
      onTap: () => _navigateToDetail(spot),
      child: Container(
        margin: const EdgeInsets.only(bottom: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha((0.05 * 255).round()),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Image Section
            _buildSpotImages(spot),

            // Content Section
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Title and Rating
                  Row(
                    children: [
                      Expanded(
                        child: GestureDetector(
                          onTap: () => _navigateToDetail(spot),
                          child: Text(
                            spot.name,
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: Colors.black87,
                            ),
                          ),
                        ),
                      ),
                      _buildRatingBadge(spot.rating, spot.reviewCount),
                    ],
                  ),

                  const SizedBox(height: 8),

                  // Distance and Status
                  Row(
                    children: [
                      Icon(Icons.location_on, size: 16, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '距离${spot.distance}公里',
                        style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                      ),
                      const SizedBox(width: 16),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 8, vertical: 2),
                        decoration: BoxDecoration(
                          color: spot.isOpen ? Colors.green[50] : Colors.red[50],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          spot.isOpen ? '营业中' : '已关闭',
                          style: TextStyle(
                            fontSize: 12,
                            color:
                                spot.isOpen ? Colors.green[600] : Colors.red[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 8),

                  // Description
                  Text(
                    spot.description,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[700],
                      height: 1.4,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),

                  const SizedBox(height: 12),

                  // Fish Types
                  _buildFishTypes(spot.fishTypes),

                  const SizedBox(height: 12),

                  // Facilities and Price
                  Row(
                    children: [
                      Expanded(
                        child: _buildFacilities(spot),
                      ),
                      Text(
                        spot.priceRange,
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue[600],
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 12),

                  // Action Buttons
                  Row(
                    children: [
                      Expanded(
                        child: OutlinedButton.icon(
                          onPressed: () => _showSpotDetails(spot),
                          icon: const Icon(Icons.info_outline, size: 18),
                          label: const Text('详情'),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () => _navigateToDetail(spot),
                          icon: const Icon(Icons.event, size: 18),
                          label: const Text('预订'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue[600],
                            foregroundColor: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSpotImages(FishingSpot spot) {
    if (spot.images.isEmpty) {
      return GestureDetector(
        onTap: () => _navigateToDetail(spot),
        child: Container(
          height: 200,
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: Center(
            child: Icon(
              Icons.image_not_supported,
              size: 60,
              color: Colors.grey[400],
            ),
          ),
        ),
      );
    }

    // 只显示第一张图片
    return GestureDetector(
      onTap: () => _navigateToDetail(spot),
      child: ClipRRect(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
        child: Image.network(
          spot.images[0],
          height: 200,
          width: double.infinity,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              height: 200,
              color: Colors.grey[200],
              child: Center(
                child: Icon(
                  Icons.image_not_supported,
                  size: 60,
                  color: Colors.grey[400],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildRatingBadge(double rating, int reviewCount) {
    if (reviewCount == 0) {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8),
        ),
        child: Text(
          '暂无评价',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
          ),
        ),
      );
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.amber[50],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.star, size: 16, color: Colors.amber[600]),
          const SizedBox(width: 4),
          Text(
            rating.toStringAsFixed(1),
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Colors.amber[800],
            ),
          ),
          Text(
            ' ($reviewCount)',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFishTypes(List<String> fishTypes) {
    return Wrap(
      spacing: 6,
      runSpacing: 6,
      children: fishTypes.take(4).map((fish) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text(
            fish,
            style: TextStyle(
              fontSize: 12,
              color: Colors.blue[600],
              fontWeight: FontWeight.w500,
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildFacilities(FishingSpot spot) {
    // 获取所有设施数据
    final allFacilities = Facility.getMockFacilities();
    
    // 根据设施ID获取对应的设施信息，只显示前3个
    final spotFacilities = spot.facilityIds
        .take(3)
        .map((id) => allFacilities.firstWhere(
              (facility) => facility.id == id,
              orElse: () => Facility(id: 0, name: '未知设施', description: ''),
            ))
        .toList();

    if (spotFacilities.isEmpty) {
      return Text(
        '暂无设施信息',
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey[500],
        ),
      );
    }

    return Wrap(
      spacing: 4,
      runSpacing: 4,
      children: spotFacilities.map((facility) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          decoration: BoxDecoration(
            color: Facility.getColorForFacility(facility.name).withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(
              color: Facility.getColorForFacility(facility.name).withOpacity(0.3),
              width: 1,
            ),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Facility.getIconForFacility(facility.name),
                size: 12,
                color: Facility.getColorForFacility(facility.name),
              ),
              const SizedBox(width: 2),
              Text(
                facility.name,
                style: TextStyle(
                  fontSize: 10,
                  color: Facility.getColorForFacility(facility.name),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  void _showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索钓场'),
        content: TextField(
          controller: _searchController,
          decoration: const InputDecoration(
            hintText: '输入钓场名称、位置或鱼类...',
            prefixIcon: Icon(Icons.search),
            border: OutlineInputBorder(),
          ),
          autofocus: true,
          onSubmitted: (value) {
            _onSearch(value);
            Navigator.of(context).pop();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              _searchController.clear();
              _onSearch('');
              Navigator.of(context).pop();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              _onSearch(_searchController.text);
              Navigator.of(context).pop();
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('过滤选项'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('难度等级:', style: TextStyle(fontWeight: FontWeight.w600)),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: [
                _buildDifficultyChip('全部', 'all'),
                _buildDifficultyChip('初级', 'beginner'),
                _buildDifficultyChip('中级', 'intermediate'),
                _buildDifficultyChip('高级', 'advanced'),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                _selectedDifficulty = 'all';
                _updateFilteredSpots();
              });
              Navigator.of(context).pop();
            },
            child: const Text('重置'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('应用'),
          ),
        ],
      ),
    );
  }

  Widget _buildDifficultyChip(String label, String value) {
    final isSelected = _selectedDifficulty == value;
    return FilterChip(
      label: Text(label),
      selected: isSelected,
      onSelected: (selected) {
        setState(() {
          _selectedDifficulty = value;
          _updateFilteredSpots();
        });
      },
      selectedColor: Colors.green[100],
      checkmarkColor: Colors.green[600],
    );
  }

  void _showSpotDetails(FishingSpot spot) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(spot.name),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('地址: ${spot.address}'),
              const SizedBox(height: 8),
              Text('营业时间: ${spot.openHours}'),
              const SizedBox(height: 8),
              Text('电话: ${spot.phone}'),
              const SizedBox(height: 8),
              Text('鱼类: ${spot.fishTypes.join(', ')}'),
              const SizedBox(height: 8),
              _buildFacilities(spot),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }



  void _navigateToDetail(FishingSpot spot) {
    context.push('/fishing/${spot.id}');
  }
}
